package com.commerce.addressbook.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;

import com.commerce.addressbook.Entity.Contacts;
import com.commerce.addressbook.Entity.DataBean;
import com.commerce.addressbook.GlobalVariable;
import com.commerce.addressbook.R;
import com.commerce.addressbook.adapter.ExpandableAdapter;
import com.commerce.addressbook.utlis.MyContentResolver;

import org.litepal.LitePal;

import java.io.File;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_EXTERNAL_STORAGE = 201;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.CAMERA
    };
    //联系人列表
    private ExpandableListView mPtrExpandableLv = null;


    private final static int CAMERA_REQUEST_CODE = 0;
    private final static int GALLERY_REQUEST_CODE = 1;
    //获取系统公共存储路径
    private String mTempPhotoPathclone;

    //适配器
    public ExpandableAdapter mAdapter = null;

    OnSelectedListener mOnSelectedListener = new OnSelectedListener() {
        @Override
        public void OnSelected(View v, int position) {
            switch (position) {
                case 0:
                    mTempPhotoPathclone= GlobalVariable.mTempPhotoPath();
                    Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    //下面这句指定调用相机拍照后的照片存储的路径
                    takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPathclone)));
                    startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
                    break;
                case 1:
                    Intent pickIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    // 打开相册
                    pickIntent.setType("image/*");
                    startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);
                    break;
                case 2:
                    break;
            }
        }
    } ;
    private List<Contacts> mParents;
    private List<List<DataBean>> mChildren;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
        //从Android 7.0开始，google修改了拍照时候数据传递，一个应用提供自身文件给其它应用使用时，
        // 如果给出一个file://格式的URI的话，应用会抛出FileUriExposedException。
        // 这是由于谷歌认为目标app可能不具有文件权限，会造成潜在的问题。所以会报错。
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }

        //刷新问题
        new MyContentResolver(this).getContactsData();
        mParents = LitePal.findAll(Contacts.class);
        mChildren = GlobalVariable.getGlobalVariable().getDataBeans();
        mAdapter = new ExpandableAdapter(this, mParents, mChildren,mOnSelectedListener);
        mPtrExpandableLv = findViewById(R.id.main_pelv_content);
        mPtrExpandableLv.setAdapter(mAdapter);
        mPtrExpandableLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, ContactsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("mParents", mParents.get(position));
                intent.putExtras(bundle);
                intent.putExtra("pos",position);
                startActivity(intent);
                return true;
            }
        });
    }

    @Override
    protected void onRestart() {
        new MyContentResolver(this).getContactsData();
        mParents.clear();
        mParents.addAll(LitePal.findAll(Contacts.class));
        mChildren.clear();
        mChildren.addAll(GlobalVariable.getGlobalVariable().getDataBeans());
        mAdapter.notifyDataSetChanged();
        super.onRestart();
    }

    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
//        GlobalVariable.getGlobalVariable().setContacts(null);
        Intent intent = new Intent(MainActivity.this, ContactsActivity.class);
        startActivity(intent);
        return super.onOptionsItemSelected(item);
    }

    /**
     * 选择监听接口
     */
    public interface OnSelectedListener {
        void OnSelected(View v, int position);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        int n = grantResults.length;
        if (n < 1)
            return ;
        for (int i = 0; i < n; i++){
            if (PackageManager.PERMISSION_GRANTED != grantResults[i]){ //用户未授予权限定义中对应的权限
                //未授权，不能执行需要权限的操作。
                finish();
            }else{
                //已授权可以执行相应操作
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE:
                    File temp = new File(mTempPhotoPathclone);
                    Uri uri = Uri.fromFile(temp);
                    Intent intent = new Intent(this, CropActivity.class);
                    intent.setData(uri);
                    startActivity(intent);
                    break;
                case GALLERY_REQUEST_CODE:
                    Uri data1 = data.getData();
                    Intent intent1 = new Intent(this,CropActivity.class);
                    intent1.setData(data1);
                    startActivity(intent1);
                    break ;
                default:
                    throw new IllegalStateException("Unexpected value: " + requestCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}